﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using Microsoft.Phone;
using SMARTMobile.Common;

namespace SMARTMobile.Utilities
{
    public static class ImageUtilities
    {
        public static void SaveToJpeg(BitmapImage bitmap, string strImageName)
        {
            try
            {
                using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (iso.FileExists(strImageName))
                    {
                        iso.DeleteFile(strImageName);
                    }

                    using (IsolatedStorageFileStream isostream = iso.CreateFile(strImageName))
                    {
                        ////PictureDecoder.DecodeJpeg(bitmap.);
                        WriteableBitmap wb = new WriteableBitmap(bitmap);
                        // Encode WriteableBitmap object to a JPEG stream. 
                        Extensions.SaveJpeg(wb, isostream, 150, 150, 0, 75);
                        isostream.Close();
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private static void SaveToJpeg1(BitmapImage bitmap, string strImageName)
        {
            try
            {
                using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (iso.FileExists(strImageName))
                    {
                        iso.DeleteFile(strImageName);
                    }

                    using (IsolatedStorageFileStream isostream = iso.CreateFile(strImageName))
                    {
                        WriteableBitmap wb = new WriteableBitmap(bitmap);
                        // Encode WriteableBitmap object to a JPEG stream. 
                        Extensions.SaveJpeg(wb, isostream, wb.PixelWidth, wb.PixelHeight, 0, 100);
                        isostream.Close();
                    }
                }
            }
            catch (Exception e)
            {
                string error = e.ToString();
            }

        }

        public static void SaveToJpeg(BitmapImage bitmap, string strImageName, string directory)
        {
            try
            {
                using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (iso.FileExists(strImageName))
                    {
                        iso.DeleteFile(strImageName);
                    }

                    iso.CreateDirectory(directory);

                    using (IsolatedStorageFileStream isostream = iso.CreateFile(strImageName))
                    {
                        WriteableBitmap wb = new WriteableBitmap(bitmap);
                        // Encode WriteableBitmap object to a JPEG stream. 
                        Extensions.SaveJpeg(wb, isostream, 150, 150, 0, 75);
                        isostream.Close();
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        public static BitmapImage LoadImageFromIsolatedStorage(string strImageName)
        {
            // The image will be read from isolated storage into the following byte array 
            byte[] data;

            // Read the entire image in one go into a byte array 
            try
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // Open the file - error handling omitted for brevity 
                    // Note: If the image does not exist in isolated storage the following exception will be generated: 
                    // System.IO.IsolatedStorage.IsolatedStorageException was unhandled  
                    // Message=Operation not permitted on IsolatedStorageFileStream  
                    ////using (IsolatedStorageFileStream isfs = isf. OpenFile(strImageName, FileMode.Open, FileAccess.Read))
                    ////{
                    ////    // Allocate an array large enough for the entire file 
                    ////    data = new byte[isfs.Length];
                    ////    // Read the entire file and then close it 
                    ////    isfs.Read(data, 0, data.Length);
                    ////    isfs.Close();
                    ////}

                    IsolatedStorageFileStream stream1 = new IsolatedStorageFileStream(strImageName, FileMode.Open, isf);
                    data = new byte[stream1.Length];
                    stream1.Read(data, 0, data.Length);
                    stream1.Close();
                }

                // Create memory stream and bitmap 
                MemoryStream ms = new MemoryStream(data);
                BitmapImage bi = new BitmapImage();
                // Set bitmap source to memory stream 
                bi.SetSource(ms);

                return bi;
            }
            catch (Exception e)
            {
                string error = e.ToString();
                return null;
            }
        }

        public static string CreateImageName()
        {
            return Guid.NewGuid().ToString() + "-Image.Jpeg";
        }

        public static MemoryStream LoadImageStreamFromIsolatedStorage(string strImageName)
        {
            // The image will be read from isolated storage into the following byte array 
            byte[] data;

            // Read the entire image in one go into a byte array 
            try
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // Open the file - error handling omitted for brevity 
                    // Note: If the image does not exist in isolated storage the following exception will be generated: 
                    // System.IO.IsolatedStorage.IsolatedStorageException was unhandled  
                    // Message=Operation not permitted on IsolatedStorageFileStream  
                    ////using (IsolatedStorageFileStream isfs = isf. OpenFile(strImageName, FileMode.Open, FileAccess.Read))
                    ////{
                    ////    // Allocate an array large enough for the entire file 
                    ////    data = new byte[isfs.Length];
                    ////    // Read the entire file and then close it 
                    ////    isfs.Read(data, 0, data.Length);
                    ////    isfs.Close();
                    ////}

                    IsolatedStorageFileStream stream1 = new IsolatedStorageFileStream(strImageName, FileMode.Open, isf);
                    data = new byte[stream1.Length];
                    stream1.Read(data, 0, data.Length);
                    stream1.Close();
                }

                // Create memory stream and bitmap 
                MemoryStream ms = new MemoryStream(data);
                ////BitmapImage bi = new BitmapImage();
                ////// Set bitmap source to memory stream 
                ////bi.SetSource(ms);

                return ms;
            }
            catch (Exception e)
            {
                string error = e.ToString();
                return null;
            }
        }

        public static string BitmapToBase64(string imageName)
        {
            MemoryStream stream = LoadImageStreamFromIsolatedStorage(imageName);
            ////byte[] imageData = new byte[stream.Length];
            ////stream.Write(imageData, 0, imageData.Length);
            return Convert.ToBase64String(stream.ToArray());
        }

        public static string ConvertBitmapToString(string imageName)
        {
            MemoryStream image = LoadImageStreamFromIsolatedStorage(imageName);
            return Convert.ToBase64String(image.ToArray());
            ////using (MemoryStream ms = new MemoryStream())
            ////{
            ////    WriteableBitmap btmMap = new WriteableBitmap(image.PixelWidth, image.PixelHeight);

            ////    btmMap.SetSource(image);
            ////    // write an image into the stream
            ////    btmMap.SaveJpeg(ms, 240, 240, 0, 100);

            ////    return Convert.ToBase64String(ms.ToArray());
            ////}
        }

        ////public static byte[] ConvertToBytes(BitmapImage bitmapImage)
        ////{
        ////    using (MemoryStream ms = new MemoryStream())
        ////    {
        ////        WriteableBitmap btmMap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);

        ////        // write an image into the stream
        ////        btmMap.SaveJpeg(ms, 240, 240, 0, 100);

        ////        return ms.ToArray();
        ////    }
        ////}

        public static bool CheckFileExist(string filePath)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists(filePath))
                    {
                        return true;
                    }

                    return false;
                }
            }
            catch (Exception e)
            {
                string error = e.ToString();
                return false;
            }
        }

        public static void DeleteAllImageFile()
        {
            try
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    List<String> imageName = GetAllFiles("*.jpeg", isf);
                    foreach (string name in imageName)
                    {
                        if (isf.FileExists(name))
                        {
                            isf.DeleteFile(name);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        public static List<String> GetAllFiles(string pattern, IsolatedStorageFile storeFile)
        {
            // Get the root and file portions of the search string. 
            string fileString = Path.GetFileName(pattern);

            List<String> fileList = new List<String>(storeFile.GetFileNames(pattern));

            // Loop through the subdirectories, collect matches, 
            // and make separators consistent. 
            foreach (string directory in GetAllDirectories("*", storeFile))
            {
                foreach (string file in storeFile.GetFileNames(directory + "/" + fileString))
                {
                    fileList.Add((directory + "/" + file));
                }
            }

            return fileList;
        }

        // Method to retrieve all directories, recursively, within a store. 
        public static List<String> GetAllDirectories(string pattern, IsolatedStorageFile storeFile)
        {
            // Get the root of the search string. 
            string root = Path.GetDirectoryName(pattern);

            if (root != "")
            {
                root += "/";
            }

            // Retrieve directories.
            List<String> directoryList = new List<String>(storeFile.GetDirectoryNames(pattern));

            // Retrieve subdirectories of matches. 
            for (int i = 0, max = directoryList.Count; i < max; i++)
            {
                string directory = directoryList[i] + "/";
                List<String> more = GetAllDirectories(root + directory + "*", storeFile);

                // For each subdirectory found, add in the base path. 
                for (int j = 0; j < more.Count; j++)
                {
                    more[j] = directory + more[j];
                }

                // Insert the subdirectories into the list and 
                // update the counter and upper bound.
                directoryList.InsertRange(i + 1, more);
                i += more.Count;
                max += more.Count;
            }

            return directoryList;
        }
    }
}
